package cfca.paperless.client.servlet._2_extend._2_03_SignAutoPdfHash;

import java.io.File;
import org.apache.commons.io.FileUtils;
import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.GUID;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.StrategyUtil;
import cfca.paperless.client.util.StringUtil;
import cfca.sadk.util.Base64;

public class SignAutoPdfHashTest01 {

    /**
     * 调用PDF自动化计算Hash接口
     * 调用hash签名接口
     * 调用合成签名接口
     * @param args
     */
    public static void main(String[] args) {
        try {
            long timeStart = System.currentTimeMillis();// 开始时间
            
            
            String sealCode = "s7";//印章编码
            String sealPassword = "cfca1234";
            
            byte[] x509Cert = null;
            
            //以下代码为获取印章编码对应公钥证书
            PaperlessClient assistClientBean = new PaperlessClient(PaperlessConfig.assistUrl, 10000, 60000);// 无纸化辅助接口的访问URL

            String result = assistClientBean.getSealInfo(sealCode, PaperlessConfig.operatorCode);
            String code = StringUtil.getNodeText(result, "Code");
            if (!code.equals("200")) {
                System.out.println("error:getSealInfo");
                System.out.println(result);
                
                long timeEnd = System.currentTimeMillis();// 结束时间
                System.out.println("time:" + (timeEnd - timeStart));
                
                return;
            } else {
                x509Cert = Base64.decode(StringUtil.getNodeText(result, "SealCert"));
                sealPassword = StringUtil.getNodeText(result, "SealPassword");
            }
            
            
            long timeEnd = System.currentTimeMillis();// 结束时间
            System.out.println("time:" + (timeEnd - timeStart));

            
            
            timeStart = System.currentTimeMillis();// 开始时间
            
            PaperlessClient extClientBean = new PaperlessClient(PaperlessConfig.extUrl, 10000, 60000);// 无纸化辅助接口的访问URL

            String filePath = "./TestData/autoCalculatePdfHash.pdf";
            byte[] pdf = FileUtils.readFileToByteArray(new File(filePath));
            
            byte[] handwritingImage = FileUtils.readFileToByteArray(new File("./TestData/zhangfei.png"));
            
            SignLocation signLocation = new SignLocation("代理人签名", "R", 10, 10);//签章位置
            
            // get pdf hash
            String strategyXml = StrategyUtil.createClientSealStrategyXml("业务", "china", handwritingImage, signLocation, "SHA1");
            String systemNo = GUID.generateId();//业务流水号 
            //计算hash x509Cert参数可以为空，为空时外部合成签名只能是pkcs7
            String returnMessage = extClientBean.autoCalculatePdfHash(systemNo,pdf, x509Cert, strategyXml, PaperlessConfig.operatorCode, PaperlessConfig.channelCode);
            
            code = StringUtil.getNodeText(returnMessage, "Code");
            if (!"200".equals(code)) {
                System.out.println("NG:autoCalculatePdfHash");
                System.out.println(returnMessage);
                
                timeEnd = System.currentTimeMillis();// 结束时间
                System.out.println("time:" + (timeEnd - timeStart));
                
                return;
            }
        
        
            System.out.println("OK:autoCalculatePdfHash");
            String pdfSealHash = StringUtil.getNodeText(returnMessage, "PdfSealHash");
            String pdfSealSource = StringUtil.getNodeText(returnMessage, "PdfSealSource");
            
            System.out.println("PdfSealHash:"+ pdfSealHash);
            
            String pdfHashSignListXml = "<List><PdfHashSign>" +
                                        "<PdfSealHash>" + pdfSealHash + "</PdfSealHash>" +
                                        "<PdfSealSource>" +pdfSealSource+"</PdfSealSource>" +
                                        "<BizTypeCode></BizTypeCode>" +
                                        "<SealCode>" + sealCode + "</SealCode>" +
                                        "<SealPassword>" + sealPassword + "</SealPassword>" +
                                        "</PdfHashSign></List>";
            String id = StringUtil.getNodeText(returnMessage, "Id");
            
            //手机号验证码
            //String authCodeXml = "<AuthCode><AuthCodeValue>150951</AuthCodeValue><AuthCodeId>201607281502489803710772387922</AuthCodeId></AuthCode>";
            
            //对pdf hash签名
            String signMessage = extClientBean.signAutoPdfHash(pdfHashSignListXml, "", PaperlessConfig.operatorCode, PaperlessConfig.channelCode);
            code = StringUtil.getNodeText(signMessage, "Code");
            if (!"200".equals(code)) {
                System.out.println("NG:signAutoPdfHash");
                System.out.println(signMessage);
                
                timeEnd = System.currentTimeMillis();// 结束时间
                System.out.println("time:" + (timeEnd - timeStart));
                
                return;
            }
        
        
            System.out.println("OK:signAutoPdfHash");
            Object[] signedBeanArr = StringUtil.getXmlFieldArr(signMessage, "SignedBean");
            
            String pkcs7 = StringUtil.getNodeText((String)signedBeanArr[0], "Pkcs7");
            System.out.println("返回的pkcs7：" + pkcs7);
 
            
            byte[] sealedPdfData = extClientBean.synthesizeOuterSignature(systemNo,Base64.decode(pkcs7), id, PaperlessConfig.operatorCode, PaperlessConfig.channelCode);
            String errorRsString = PaperlessUtil.isError(sealedPdfData);

            if ("".equals(errorRsString)) {
                System.out.println("OK:synthesizeOuterSignature");
                IoUtil.write("./TestData/output/signAutoPdfHash-" + new File(filePath).getName() + ".pdf", sealedPdfData);
            } else {
                // 处理结果为异常，打印出错误码和错误信息
                System.out.println("NG:synthesizeOuterSignature");
                System.out.println(new String(sealedPdfData, "UTF-8"));
            }
            
            timeEnd = System.currentTimeMillis();// 结束时间
            System.out.println("time:" + (timeEnd - timeStart));
            

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
